﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Net;
using System.Runtime.InteropServices;

public partial class mobile_ajaxdata_login : Page
{
    MyDbHelper mydb = new MyDbHelper();

    [DllImport("Iphlpapi.dll")]
    private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
    [DllImport("Ws2_32.dll")]
    private static extern Int32 inet_addr(string ip);

    protected void Page_Load(object sender, EventArgs e)
    {
        string aciton = Request.Params["aciton"];
        switch (aciton)
        {
            case "Login":
                UserLogin();
                break;
            case "AppLogin":
                AppLogin();
                break;
            case "GetUser":
                GetUserInfo();
                break;
            case "LoginOut":
                LoginOut();
                break;
            case "getupdate":
                getupdate();//获取最新版本
                break;
            case "getuserpwd":
                getuserpwd();
                break;
            case "updpwd":
                updpwd();
                break;
        }
    }

    private void AppLogin()
    {
        object result = null;
        string ucode = Request.Params["UserCode"];
        string pwd = Request.Params["UserPwd"];
        string type = Request.Params["LoginType"];
        string clientype = Request.Params["clientype"];
        string str = "";
        //if (clientype == "shop")
        //{
        //    str = " and apptype = 1";
        //}
        //else if (clientype == "client")
        //{
        //    str = " and apptype = 2";
        //}
        //else
        //{
        //    str = " and apptype = 0";
        //}
        DataSet ds = mydb.DM_GetDateSet("select * from sys_loginuser where usercode ='" + ucode + "' and upassword = '" + pwd + "' "+str);
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (bool.Parse(ds.Tables[0].Rows[0]["block"].ToString()))
                {
                    if (clientype == "shop")
                    {
                        if (ds.Tables[0].Rows[0]["apptype"].ToString() != "1")
                            result = new { status = 0, msg = "该用户不是店铺帐号，无法登录！" };
                        else
                        {
                            result = new
                            {
                                status = 1,
                                UserID = ds.Tables[0].Rows[0]["userid"],
                                UserCode = ds.Tables[0].Rows[0]["usercode"],
                                UserName = ds.Tables[0].Rows[0]["username"],
                            };
                            InsLoginLog(ds.Tables[0].Rows[0]["userid"].ToString(),
                                ds.Tables[0].Rows[0]["usercode"].ToString(),
                            ds.Tables[0].Rows[0]["username"].ToString(), type, Request.UserHostAddress);
                        }
                    }
                    else if (clientype == "client")
                    {
                        if (ds.Tables[0].Rows[0]["apptype"].ToString() != "2")
                            result = new { status = 0, msg = "该用户不是加盟商帐号，无法登录！" };
                        else
                        {
                            result = new
                            {
                                status = 1,
                                UserID = ds.Tables[0].Rows[0]["userid"],
                                UserCode = ds.Tables[0].Rows[0]["usercode"],
                                UserName = ds.Tables[0].Rows[0]["username"],
                            };
                            InsLoginLog(ds.Tables[0].Rows[0]["userid"].ToString(),
                                ds.Tables[0].Rows[0]["usercode"].ToString(),
                            ds.Tables[0].Rows[0]["username"].ToString(), type, Request.UserHostAddress);
                        }
                    }
                }
                else
                {
                    result = new { status = 0, msg = "该帐号已被停用！" };
                }
            }
            else
            {
                result = new { status = 0, msg = "用户名或者密码错！" };
            }
        }
        else
        {
            result = new { status = 0, msg = "登录出现错误！" };
        }
        Response.Write(JsonHelper.SerializeObject(result));
        Response.End();
    }

    private void updpwd()
    {
        string userid = Request.Params["userid"];
        string pwd = Request.Params["pwd"];
        if (mydb.DM_ExecuteNonQuery("update sys_loginuser set upassword ='" + pwd + "'  where userid=" + userid ) != -1)
        {
            Response.Write("OK");
            Response.End();
        }
        else
        {
            Response.Write("NO_ERR");
            Response.End();
        }
    }

    private void getuserpwd()
    {
        string userid= Request.Params["userid"];
        string pwd= Request.Params["pwd"];
        string sql = "select * from sys_loginuser where userid=" + userid + " and upassword ='" + pwd + "'";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            Response.Write("OK");
            Response.End();
        }
        else
        {
            Response.Write("NO_DATA");
            Response.End();
        }
    }

    private void getupdate()
    {
        if (Request["ClientType"] != null && Request["ClientType"] != ""
            && Request["Version"] != null && Request["Version"] != "")
        {
            if (Request["ClientType"].ToString() == "android")
            {
                Response.Write("{version:'20160315',size:'2.8M',url:'/android/KMRTPAPP.apk',msg:''}");
            }
            else if (Request["ClientType"].ToString() == "iphone")
            {
                Response.Write("{version:'20140417',size:'5.93M',url:'#',msg:'敬请期待'}");
            }
            Response.End();
        }
    }
    private void UserLogin()
    {
        string ucode = Request.Params["UserCode"];
        string pwd = Request.Params["UserPwd"];
        string type = Request.Params["LoginType"];
        //string mac = GetMac(); 
        DataSet ds = mydb.DM_GetDateSet("select * from sys_loginuser where usercode ='" + ucode + "'");
        if (ds.Tables[0].Rows.Count > 0)
        {
            DataRow dr = ds.Tables[0].Rows[0];

            //查检密码
            string des_wpd = "";
            //if (bool.Parse(dr["UpPwd"].ToString()))
            //    des_wpd = SDKSecurity.DESDecrypt(dr["upassword"].ToString(), "km141201");
            //else
            //    des_wpd = dr["upassword"].ToString();
            des_wpd = SDKSecurity.DESDecrypt(dr["upassword"].ToString(), "km141201");
            if (pwd.ToLower() != des_wpd.ToLower())
            {
                Response.Write("err_text");
                Response.End();
                return;
            }
            System.Data.DataTable userTable = (System.Data.DataTable)Application["OnlineUsers"];
            if (userTable == null)
                return;
            System.Data.DataRow[] curRow = userTable.Select("UserCode='" + ucode + "'");

            if (curRow.Length > 0)
            {
                Response.Write("user_lock");
                Response.End();
                return;
            }
            if (bool.Parse(dr["block"].ToString()))
            {
                string sbr = "";
                sbr = "[";

                sbr += "{\"UserID\":\"" + dr["userid"]
                    + "\",\"UserCode\":\"" + dr["usercode"]
                    + "\",\"UserName\":\"" + dr["username"]
                        + "\"},";
                sbr = sbr.TrimEnd(',') + "]";

                Session["UserID"] = dr["userid"];
                Session["UserCode"] = dr["usercode"];
                Session["UserName"] = dr["username"];
                string userid = dr["userid"].ToString();
                
                InsLoginLog(userid,dr["usercode"].ToString(),dr["username"].ToString(), type, Request.UserHostAddress);

                Response.Write(sbr);
                Response.End();
            }
            else
            {
                Response.Write("user_stop");
                Response.End();
            }
        }
        else
        {
            Response.Write("err_text");
            Response.End();
        }
    }

    private void LoginOut()
    {
        string UserCode = Request.Params["UserCode"];
        System.Data.DataTable userTable = (System.Data.DataTable)Application["OnlineUsers"];

        if (userTable == null)

            return;

        foreach (System.Data.DataRow row in userTable.Select("UserCode='" + UserCode + "'"))
        {

            userTable.Rows.Remove(row);

        }

        userTable.AcceptChanges();

        Application.Lock();

        Application["OnlineUsers"] = userTable;

        Application.UnLock(); 

        Session.Clear();//从Session状态集合中移除所有的键和值。 
        Session.Abandon();//取消当前Session会话  
    }

    private void GetUserInfo()
    {
        if (Session["UserCode"] == null || Session["UserCode"] == "")
        {
            Response.Write("NOUSER");
            Response.End();
        }
        else
        {
            string sbr = "";
            sbr = "[";

            sbr += "{\"UserCode\":\"" + Session["UserCode"]
                    + "\",\"UserName\":\"" + Session["UserName"]
                    + "\"},";
            sbr = sbr.TrimEnd(',') + "]";
            Response.Write(sbr);
            Response.End();
        }
        return;
    }

    public void InsLoginLog(string UserID,string UserCode,string UserName, string LoginType,string userIP)
    {
        string sql = @"insert into sys_loginlog(userid,logintype,loginip)
                        values(" + UserID + ",'" + LoginType + "','" + userIP + "')";
        mydb.DM_ExecuteNonQuery(sql);
        System.Data.DataTable userTable = (System.Data.DataTable)Application["OnlineUsers"];

        if (userTable == null)

            return;

        System.Data.DataRow[] curRow = userTable.Select("UserCode='" + UserCode + "'");

        if (curRow.Length == 0)
        {

            System.Data.DataRow row = userTable.NewRow();

            row["SessionID"] = Session.SessionID;
            row["UserCode"] = UserCode;
            row["UserName"] = UserName;
            row["UserIP"] = userIP;
            row["Browser"] = Request.Browser;
            row["OSName"] = LoginType;
            userTable.Rows.Add(row);
            userTable.AcceptChanges();

            Application.Lock();

            Application["OnlineUsers"] = userTable;

            Application.UnLock();

        }
    }

    static string GetLocalIp()
    {
        string hostname = Dns.GetHostName();
        IPHostEntry localhost = Dns.GetHostByName(hostname);
        IPAddress localaddr = localhost.AddressList[0];
        return localaddr.ToString();
    }
    //获取MAC地址
    private string GetMac()
    {
        // 在此处放置用户代码以初始化页面
        try
        {
            string userip = Request.UserHostAddress;
            string strClientIP = Request.UserHostAddress.ToString().Trim();
            Int32 ldest = inet_addr(strClientIP); //目的地的ip 
            Int32 lhost = inet_addr("");   //本地服务器的ip 
            Int64 macinfo = new Int64();
            Int32 len = 6;
            int res = SendARP(ldest, 0, ref macinfo, ref len);
            string mac_src = macinfo.ToString("X");
            if (mac_src == "0")
            {
                return "123";
            }
            while (mac_src.Length < 12)
            {
                mac_src = mac_src.Insert(0, "0");
            }
            string mac_dest = "";
            for (int i = 0; i < 11; i++)
            {
                if (0 == (i % 2))
                {
                    if (i == 10)
                    {
                        mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                    else
                    {
                        mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                }
            }
            return mac_dest;
        }
        catch (Exception err)
        {
            Response.Write(err.Message);
            return "";    
        }

    }
}